import Toast from '/tdesign-miniprogram/toast/index';
import {
  fetchGood
} from '../../../services/good/fetchGood';
import {
  fetchActivityList
} from '../../../services/activity/fetchActivityList';
import {
  getGoodsDetailsCommentList,
  getGoodsDetailsCommentsCount,
} from '../../../services/good/fetchGoodsDetailsComments';
import {
  resource
} from '../../../static/resource';
import {
  cdnBase
} from '../../../config/index';
import {
  ds
} from '../../../tools/data';
import {
  cartTool
} from '../../../tools/cartTool'
import {
  users
} from '../../../tools/users'
import {
  ui
} from '../../../tools/ui'
import {
  dsFiles
} from '../../../tools/dsFiles';
import {
  adv
} from '../../../tools/adv';

const imgPrefix = `${cdnBase}/`;

const recLeftImg = `${imgPrefix}common/rec-left.png`;
const recRightImg = `${imgPrefix}common/rec-right.png`;
const obj2Params = (obj = {}, encode = false) => {
  const result = [];
  Object.keys(obj).forEach((key) =>
    result.push(`${key}=${encode ? encodeURIComponent(obj[key]) : obj[key]}`),
  );

  return result.join('&');
};

Page({
  data: {
    user: null,
    resource,
    commentsList: [],
    commentsStatistics: {
      badCount: 0,
      commentCount: 0,
      goodCount: 0,
      goodRate: 0,
      hasImageCount: 0,
      middleCount: 0,
    },
    isShowPromotionPop: false,
    activityList: [],
    recLeftImg,
    recRightImg,
    details: {},
    goodsTabArray: [{
        name: '商品',
        value: '', // 空字符串代表置顶
      },
      {
        name: '详情',
        value: 'goods-page',
      },
    ],
    storeLogo: `${imgPrefix}common/store-logo.png`,
    storeName: '云mall标准版旗舰店',
    jumpArray: [{
        title: '首页',
        url: '/pages/home/home',
        iconName: 'home',
      },
      {
        title: '购物车',
        url: '/pages/cart/index',
        iconName: 'cart',
        showCartNum: true,
      },
    ],
    isStock: true,
    cartNum: 0,
    soldout: false,
    buttonType: 1,
    buyNum: 1,
    selectedAttrStr: '',
    skuArray: [],
    primaryImage: '',
    specImg: '',
    isSpuSelectPopupShow: false,
    isAllSelectedSku: false,
    buyType: 0,
    outOperateStatus: false, // 是否外层加入购物车
    operateType: 0,
    selectSkuSellsPrice: 0,
    maxLinePrice: 0,
    minSalePrice: 0,
    maxSalePrice: 0,
    list: [],
    spuId: '',
    navigation: {
      type: 'fraction'
    },
    current: 0,
    autoplay: true,
    duration: 500,
    interval: 5000,
    soldNum: 0, // 已售数量
  },

  handlePopupHide() {
    this.setData({
      isSpuSelectPopupShow: false,
    });
  },

  showSkuSelectPopup(type) {
    this.setData({
      buyType: type || 0,
      outOperateStatus: type >= 1,
      isSpuSelectPopupShow: true,
    });
  },

  buyItNow() {
    this.showSkuSelectPopup(1);
  },

  toAddCart() {
    this.showSkuSelectPopup(2);
  },

  toNav(e) {
    const {
      url
    } = e.detail;
    wx.switchTab({
      url: url,
    });
  },
  showCurImg(e) {
    const {
      index
    } = e.detail;
    const {
      images
    } = this.data.details;
    wx.previewImage({
      current: images[index],
      urls: images, // 需要预览的图片http链接列表
    });
  },
  onPageScroll({
    scrollTop
  }) {
    const goodsTab = this.selectComponent('#goodsTab');
    goodsTab && goodsTab.onScroll(scrollTop);
  },

  chooseSpecItem(e) {
    const {
      specList
    } = this.data.details;
    const {
      selectedSku,
      isAllSelectedSku
    } = e.detail;

    if (!isAllSelectedSku) {
      this.setData({
        selectSkuSellsPrice: 0,
      });
    }
    this.setData({
      isAllSelectedSku,
    });
    this.getSkuItem(specList, selectedSku);
  },

  getSkuItem(specList, selectedSku) {
    const {
      skuArray,
      primaryImage
    } = this.data;
    const selectedSkuValues = this.getSelectedSkuValues(specList, selectedSku);
    let selectedAttrStr = ` 件  `;
    selectedSkuValues.forEach((item) => {
      selectedAttrStr += `，${item.specValue}  `;
    });
    // eslint-disable-next-line array-callback-return
    const skuItem = skuArray.filter((item) => {
      let status = true;
      (item.specInfo || []).forEach((subItem) => {
        if (
          !selectedSku[subItem.specId] ||
          selectedSku[subItem.specId] !== subItem.specValueId
        ) {
          status = false;
        }
      });
      if (status) return item;
    });
    this.selectSpecsName(selectedSkuValues.length > 0 ? selectedAttrStr : '');

    if (skuItem) {
      this.setData({
        selectItem: skuItem,
        selectSkuSellsPrice: skuItem[0]?.price || 0,
      });
      // console.log(skuItem)
    } else {
      this.setData({
        selectItem: null,
        selectSkuSellsPrice: 0,
      });
    }
    this.setData({
      specImg: skuItem && skuItem.skuImage ? skuItem.skuImage : primaryImage,
    });
  },

  // 获取已选择的sku名称
  getSelectedSkuValues(skuTree, selectedSku) {
    const normalizedTree = this.normalizeSkuTree(skuTree);
    return Object.keys(selectedSku).reduce((selectedValues, skuKeyStr) => {
      const skuValues = normalizedTree[skuKeyStr];
      const skuValueId = selectedSku[skuKeyStr];
      if (skuValueId !== '') {
        const skuValue = skuValues.filter((value) => {
          return value.specValueId === skuValueId;
        })[0];
        skuValue && selectedValues.push(skuValue);
      }
      return selectedValues;
    }, []);
  },

  normalizeSkuTree(skuTree) {
    const normalizedTree = {};
    skuTree.forEach((treeItem) => {
      normalizedTree[treeItem.specId] = treeItem.specValueList;
    });
    return normalizedTree;
  },

  selectSpecsName(selectSpecsName) {
    if (selectSpecsName) {
      this.setData({
        selectedAttrStr: selectSpecsName,
      });
    } else {
      this.setData({
        selectedAttrStr: '',
      });
    }
  },

  addCart(e) {
    const {
      isAllSelectedSku
    } = this.data;
    // console.log(this.data)
    if (!isAllSelectedSku) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '请选择规格',
        icon: '',
        duration: 1000,
      });
      return
    }

    // console.log(this.data)
    cartTool.add({
      ...this.data.item,
      selectItem: this.data.selectItem,
      vip: this.data.item.userInfo?.vip || false,
      buyNum: this.data.buyNum
    })

  },

  gotoBuy(type) {
    const {
      isAllSelectedSku,
      buyNum,
      goods
    } = this.data;
    if (!isAllSelectedSku) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '请选择规格',
        icon: '',
        duration: 1000,
      });
      return;
    }
    // console.log(this.data)
    this.handlePopupHide();
    const query = {
      quantity: buyNum,
      storeId: '1',
      fastDelivery: goods.fastDelivery,
      spuId: this.data.spuId,
      goodsName: this.data.details.title,
      skuId: type === 1 ? this.data.skuList[0].skuId : this.data.selectItem.skuId,
      available: this.data.details.available,
      price: this.data.selectSkuSellsPrice,
      specInfo: [{
        specTitle: this.data.selectItem[0].skuId,
        specValue: this.data.selectItem[0].skuId,
      }],
      primaryImage: this.data.details.primaryImage,
      spuId: this.data.details.spuId,
      thumb: this.data.details.primaryImage,
      title: this.data.details.title,
    };

    // console.log(query);
    let urlQueryStr = obj2Params({
      goodsRequestList: JSON.stringify([query]),
      vipPrice: this.data.vipPrice
    });
    urlQueryStr = urlQueryStr ? `?${urlQueryStr}` : '';
    const path = `/pages/order/order-confirm/index${urlQueryStr}`;
    const ticket = JSON.stringify(this.data.details.ticket)
    const ticketParam = (this.data.showTicket ? `&ticketOrder=true&ticket=${ticket}` : '')
    // console.log(this.data.details)
    wx.navigateTo({
      url: path + ticketParam,
    });
  },

  specsConfirm() {
    const {
      buyType
    } = this.data;
    if (buyType === 1) {
      this.gotoBuy();
    } else {
      this.addCart();
    }
    // this.handlePopupHide();
  },

  changeNum(e) {
    this.setData({
      buyNum: e.detail.buyNum,
    });
  },

  closePromotionPopup() {
    this.setData({
      isShowPromotionPop: false,
    });
  },

  promotionChange(e) {
    const {
      index
    } = e.detail;
    wx.navigateTo({
      url: `/pages/promotion-detail/index?promotion_id=${index}`,
    });
  },

  showPromotionPopup() {
    this.setData({
      isShowPromotionPop: true,
    });
  },

  // 数据准备
  getDetail(spuId) {
    const item = this.data.item
    const vip = item.userInfo?.vip || false
    const showTicket = this.data.showTicket
    // console.log(item)
    Promise.all([fetchGood(spuId), fetchActivityList()]).then((res) => {
      let minPrice = -1,
        maxPrice = -1
      item.specList.forEach(ele => {
        const nPrice = Number(ele.price),
          nOriPrice = Number(ele.originPrice)
        if (minPrice < 0 || nPrice < minPrice) minPrice = (vip && ele.vipPrice ? Number(ele.vipPrice) : nPrice)
        if (maxPrice < 0 || nOriPrice > maxPrice) maxPrice = nOriPrice
      })

      const specId = '1010'
      let specValues = [],
        skus = []
      item.specList.forEach(ele => {
        specValues.push({
          specValueId: ele.specName,
          specValue: ele.specName
        })
        skus.push({
          skuId: ele.specName,
          skuImage: item.images[0],
          specInfo: [{
            specId: specId,
            specTitle: null,
            specValueId: ele.specName,
            specValue: null,
          }],
          stockInfo: {
            stockQuantity: 1,
            safeStockQuantity: 0,
            soldQuantity: 0,
          },
          price: (vip ? ele.vipPrice : ele.price) // 当前类型的价格
        })
      })

      // const [details, activityList] = res;
      const details = {
        saasId: '88888888',
        storeId: '1000',
        spuId,
        title: item.title,
        primaryImage: item.images[0],
        images: showTicket ? [item.ticket.image] : item.images,
        ticket: item.ticket,
        video: null,
        available: 1,
        minSalePrice: minPrice,
        minLinePrice: minPrice,
        maxSalePrice: maxPrice,
        maxLinePrice: maxPrice,
        spuStockQuantity: 510,
        soldNum: item.soldNum || 0, // 已售
        isPutOnSale: item.quantity, // 售罄
        categoryIds: [
          '127880527393854975',
          '127880527393854976',
          '127880537778953984',
        ],
        specs: item.specList,
        specList: [{
          specId: specId,
          title: '',
          specValueList: specValues
        }, ],
        skuList: skus,
        spuTagList: [{
          id: '13001',
          title: '限时抢购',
          image: null
        }],
        limitInfo: [{
          text: item.quantity ? `剩余${item.quantity}件` : '',
        }, ],
        desc: item.desc,
        etitle: '',
      }
      const key = 2
      const activityList = [{
        tag: maxPrice > minPrice ? ((minPrice * 10.0 / maxPrice).toFixed(1) + '折起') : '',
      }]

      if (showTicket) {
        activityList.push({
          tag: `每满${item.ticket.unit}桶赠${item.ticket.gift}桶`
        })
      }

      const skuArray = [];
      const {
        skuList,
        primaryImage,
        isPutOnSale,
        minSalePrice,
        maxSalePrice,
        maxLinePrice,
        soldNum,
      } = details;
      skuList.forEach((ele) => {
        skuArray.push({
          skuId: ele.skuId,
          quantity: ele.stockInfo ? ele.stockInfo.stockQuantity : 0,
          specInfo: ele.specInfo,
          price: ele.price
        });
      });
      const promotionArray = [];
      details.types = dsFiles.descFileTypeList(details.desc)
      this.setData({
        details,
        activityList, // []
        isStock: details.spuStockQuantity > 0,
        maxSalePrice: maxSalePrice ? parseInt(maxSalePrice) : 0,
        maxLinePrice: maxLinePrice ? parseInt(maxLinePrice) : 0,
        minSalePrice,
        list: promotionArray, // []
        skuArray: skuArray,
        primaryImage,
        soldout: isPutOnSale === 0,
        soldNum,
        vipPrice: vip,
      });
    });
  },
  async getCommentsList() {
    try {
      const code = 'Success';
      const data = await getGoodsDetailsCommentList();
      const {
        homePageComments
      } = data;
      if (code.toUpperCase() === 'SUCCESS') {
        const nextState = {
          commentsList: homePageComments.map((item) => {
            return {
              goodsSpu: item.spuId,
              userName: item.userName || '',
              commentScore: item.commentScore,
              commentContent: item.commentContent || '用户未填写评价',
              userHeadUrl: item.isAnonymity ?
                this.anonymityAvatar : item.userHeadUrl || this.anonymityAvatar,
            };
          }),
        };
        this.setData(nextState);
      }
    } catch (error) {
      console.error('comments error:', error);
    }
  },

  async onShareAppMessage() {
    const {
      item,
      spuId,
      showTicket
    } = this.data
    // console.log(this.data)

    const user = await this.loadUser()
    const customInfo = {
      imageUrl: this.data.details.primaryImage,
      title: item.title,
      path: `/pages/goods/details/index?spuId=${spuId}&showTicket=${ds.checkTrue(showTicket)?'true':''}&shareUserOpenid=${user._openid}`,
    };
    return customInfo;
  },

  /** 获取评价统计 */
  async getCommentsStatistics() {
    try {
      const code = 'Success';
      const data = await getGoodsDetailsCommentsCount();
      if (code.toUpperCase() === 'SUCCESS') {
        const {
          badCount,
          commentCount,
          goodCount,
          goodRate,
          hasImageCount,
          middleCount,
        } = data;
        const nextState = {
          commentsStatistics: {
            badCount: parseInt(`${badCount}`),
            commentCount: parseInt(`${commentCount}`),
            goodCount: parseInt(`${goodCount}`),
            /** 后端返回百分比后数据但没有限制位数 */
            goodRate: Math.floor(goodRate * 10) / 10,
            hasImageCount: parseInt(`${hasImageCount}`),
            middleCount: parseInt(`${middleCount}`),
          },
        };
        this.setData(nextState);
      }
    } catch (error) {
      console.error('comments statiistics error:', error);
    }
  },

  /** 跳转到评价列表 */
  navToCommentsListPage() {
    wx.navigateTo({
      url: `/pages/goods/comments/index?spuId=${this.data.spuId}`,
    });
  },

  async loadGoods(spuId) {
    const goodsRes = await ds.coll('goods')
      .where({
        _id: spuId
      })
      .get()
    const goods = goodsRes.data[0]
    const readOnly = !this.showTicket && (goods.visible == false || goods.visible == "false") && !goods.promotion && !goods.fastDelivery
    // console.log(this.showTicket, item.visible, readOnly)
    this.setData({
      item: goodsRes.data[0],
      goods,
      readOnly,
      buyNum: goods.minNum ?? 1
    })
    if (readOnly) {
      wx.setNavigationBarTitle({
        title: goods.title,
      })
    }
  },
  async loadUser() {
    if (this.data.user?._openid) return this.data.user

    const {
      item
    } = this.data
    const userInfo = await users.getUserInfo()
    item.userInfo = userInfo
    this.setData({
      item,
      user: userInfo
    })
    return userInfo
  },
  initChat() {
    const {
      item,
      showTicket
    } = this.data
    const userInfo = item.userInfo
    // console.log(item)
    this.setData({
      item,
      chatTarget: ['admin', 'master'].indexOf(userInfo.role) >= 0 ? 'list' : 'self',
      sessionOpenId: item.userInfo._openid,
      autoMsg: {
        showTicket,
        goodsId: item._id,
        title: item.title
      }
    })
    const ichat = this.selectComponent('#i-chat')
    ichat?.refresh && ichat.refresh()
  },
  async onLoad(options) { // { spuId || id, showTicket, shareUserOpenid }
    ui.loading()
    const spuId = options.spuId || options.id
    const showTicket = ds.checkTrue(options.showTicket)
    this.setData({
      spuId,
      showTicket,
      shareUserOpenid: options.shareUserOpenid
    })
    // console.log(options)
    this.showTicket = showTicket
    if (showTicket) {
      const jumpArray = this.data.jumpArray
      jumpArray[0].title = '水票'
      jumpArray[1].url = ''
      this.setData({
        jumpArray,
        buyNum: 10
      })
    }

    await this.loadGoods(spuId)
    await this.loadUser()
    this.initChat()
    this.getDetail(spuId)
    ui.loading(false)

    // console.log(options)
    this.bindStaff()

    // this.getCommentsList(spuId);
    // this.getCommentsStatistics(spuId);
  },
  async bindStaff() {
    const {
      shareUserOpenid
    } = this.data
    if (!shareUserOpenid) return

    const user = await this.loadUser()
    const res = await adv.bind(user._openid, shareUserOpenid)
    // console.log(res)
  },
});